package com.cpe.web.controller.student;

import static com.sql.data.domain.user.UserRespCode.*;
import static com.sql.data.response.CommonRespCode.*;
import static org.springframework.web.bind.annotation.RequestMethod.*;
import static com.cpe.data.domain.student.StudentRespCode.*;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cpe.data.domain.member.Member;
import com.cpe.data.domain.student.Student;
import com.cpe.data.domain.student.StudentForm;
import com.cpe.data.domain.student.StudentQuery;
import com.cpe.data.domain.student.StudentWithPhysiqueInfo;
import com.cpe.data.domain.student.StudentWithPhysiqueQuery;
import com.cpe.repository.mapper.member.MemberMapper;
import com.cpe.repository.mapper.student.StudentMapper;
import com.cpe.service.student.StudentService;
import com.cpe.transfer.student.StudentTransfer;
import com.cpe.web.controller.AbstractController;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sql.data.response.JsonResponse;

import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/students")
public class StudentController extends AbstractController {

	@Resource
	private StudentTransfer studentTransfer;

	@Resource
	private StudentMapper studentMapper;

	@Resource
	private StudentService studentService;

	@Resource
	private MemberMapper memberMapper;

	/**
	 * 添加
	 */
	@RequestMapping(method = POST)
	public JsonResponse add(@RequestBody StudentForm studentForm, HttpSession session, @RequestHeader String openid) {
		// 登录校验
		Member member = (Member) session.getAttribute("loginer");
		if (member == null) {
			// 尝试从Header里读取openid
			member = memberMapper.findByOpenid(openid);
			if (member == null) {
				return JsonResponse.custom(INVALID_TOKEN);
			}
		}

		// 权限校验
		if (member.getRole() != 1) {
			return JsonResponse.custom(PERMISSION_DENY);
		}

		// 参数校验
		if (studentForm.stopCreate()) {
			return JsonResponse.invalid("缺少必输项！");
		}

		// 数据库校验
		Student query = new Student();
		query.setName(studentForm.getName());
		query.setParentMobile(studentForm.getParentMobile());
		if (studentMapper.findOne(query) != null) {
			return JsonResponse.custom(REPEAT_INFO);
		}

		try {
			Student student = studentTransfer.toEntity(studentForm);
			studentService.addOne(student, false);
		} catch (Exception e) {
			log.info(e.getMessage(), e);
			return JsonResponse.custom(SEND_MESSAGE_FAIL);
		}
		return JsonResponse.ok();
	}

	/**
	 * 当前登录者编辑自己孩子的信息
	 */
	@RequestMapping(value = "/{id}/edit", method = PUT)
	public JsonResponse edit(@RequestBody StudentForm studentForm, HttpSession session, @RequestHeader String openid,
			@PathVariable String id) {
		// 登录校验
		Member member = (Member) session.getAttribute("loginer");
		if (member == null) {
			// 尝试从Header里读取openid
			member = memberMapper.findByOpenid(openid);
			if (member == null) {
				return JsonResponse.custom(INVALID_TOKEN);
			}
		}
		studentForm.setParentId(member.getId());
		studentForm.setParentMobile(member.getMobile());

		// 权限校验
		if (member.getRole() != 0) {
			return JsonResponse.custom(PERMISSION_DENY);
		}

		// 数据库校验
		Student student = studentMapper.findById(id);
		if (student == null) {
			return JsonResponse.custom(RESOURCE_NOT_FOUND);
		}

		try {
			student = studentTransfer.toUpdateEntity(student, studentForm);
			studentMapper.updateById(student);
			return JsonResponse.ok();
		} catch (Exception e) {
			log.info(e.getMessage(), e);
			return JsonResponse.custom(SEND_MESSAGE_FAIL);
		}
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/{id}", method = PUT)
	public JsonResponse update(@RequestBody StudentForm studentForm, HttpSession session, @RequestHeader String openid,
			@PathVariable String id) {
		// 登录校验
		Member member = (Member) session.getAttribute("loginer");
		if (member == null) {
			// 尝试从Header里读取openid
			member = memberMapper.findByOpenid(openid);
			if (member == null) {
				return JsonResponse.custom(INVALID_TOKEN);
			}
		}

		// 权限校验
		if (member.getRole() != 0) {
			return JsonResponse.custom(PERMISSION_DENY);
		}

		// 数据库校验
		Student student = studentMapper.findById(id);
		if (student == null) {
			return JsonResponse.custom(RESOURCE_NOT_FOUND);
		}

		try {
			student = studentTransfer.toUpdateEntity(student, studentForm);
			studentMapper.updateById(student);
			return JsonResponse.ok();
		} catch (Exception e) {
			log.info(e.getMessage(), e);
			return JsonResponse.custom(SEND_MESSAGE_FAIL);
		}
	}

	/**
	 * 获取详情
	 */
	@RequestMapping(value = "/{id}", method = GET)
	public JsonResponse update(@PathVariable String id) {
		Student student = studentMapper.findById(id);
		if (student == null) {
			return JsonResponse.custom(RESOURCE_NOT_FOUND);
		}
		return JsonResponse.ok(studentTransfer.toInfo(student));
	}

	/**
	 * 分页条件查询
	 */
	@RequestMapping(method = GET)
	public JsonResponse getPage(StudentQuery query) {
		try {
			// 拼接查询条件
			Student student = new Student();
			if (StringUtil.isNotBlank(query.getParentId())) {
				student.setParentId(query.getParentId());
			}
			if (StringUtil.isNotBlank(query.getClassId())) {
				student.setClassId(query.getClassId());
			}

			// 进行分页查询
			PageHelper.startPage(query.pageWhitoutOrder());
			List<Student> students = studentMapper.find(student);
			return JsonResponse.ok(studentTransfer.toPageInfo(students));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return JsonResponse.custom(EXCEPTION);
		}
	}

	/**
	 * 查询指定班级的学生，并关联查询出每个学生当天指定体质项目下的分数
	 */
	@RequestMapping(value = "/info_with_physique", method = GET)
	public JsonResponse getPageWithPhysique(StudentWithPhysiqueQuery query) {
		try {
			// 进行分页查询
			PageHelper.startPage(query.pageWhitoutOrder());
			List<StudentWithPhysiqueInfo> students = studentMapper.findInfoWithPhysiqueByClass(query);
			return JsonResponse.ok(new PageInfo<>(students));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return JsonResponse.custom(EXCEPTION);
		}
	}
}
